﻿#Requires -Version 3

#######################################################################################################################                        
# Using the Yammer API using PowerShell                        
# Author: Stefan Stranger            
# Disclamer: This program source code is provided "AS IS" without warranty representation or condition of any kind
#            either express or implied, including but not limited to conditions or other terms of merchantability and/or
#            fitness for a particular purpose. The user assumes the entire risk as to the accuracy and the use of this
#            program code.
# Tested on PowerShell v3
# You need to request a Yammer API Key at http://www.yammer.com/client_applications/new.
# You can check your Applications on https://www.yammer.com/client_applications/
# Use the Consumer key and Consumer secret from the Client application your registered.
# Download the DevDefined.OAuth.dll for OAuth from http://code.google.com/p/devdefined-tools/downloads/list
# Unzip Jammer.zip to a folder and run the Jammer.ps1 PowerShell dot sourced to have the Jammer Functions exposed in
# your current session.
# Example: . c:\Jammer\Jammer.ps1 [dot space]
# Date:		10-20-2012                        
# Name: 	Jammer.ps1            
# v1.00 - 	10-20-2012 - Stefan Stranger - sstranger's beta release
# v1.01 -   01-02-2013 - Stefan Stranger - Added support for User Group Memberships. 
# v1.02 -   28-06-2013 - Stefan Stranger - Added emailaddress property for Get-YammerUser function
#                                        - Added ID parameter for Get-YammerUser Function          
########################################################################################################################

#Set-StrictMode -Version Latest


########################################################################################################################
# Set-YammerAuthentication
# For the Yammer Authentication you need to use your own Client Application Consumer key and Consumer Secret
# Request your Yammer API Key at http://www.yammer.com/client_applications/new
########################################################################################################################
Function Set-YammerAuthentication
{
<#
.SYNOPSIS
   Authenticate with Yammer using oAuth
.DESCRIPTION
   To use this function and the other Yammer PowerShell Functions you first need to register your Application on
   https://www.yammer.com/client_applications/new
   After you have registered your Yammer Application you should use the Consumer and Consumer Secret keys
   in this PowerShell Yammer Module.
   When running the Set-YammerAuthentication Function for the first time the Yammer Consumer and Consumer Secret keys
   are stored in the registry.
   Next time you use the Set-YammerAuthentication Function it searches the registry for the Consumer and Consumer Secret keys.
.EXAMPLE
  Set-YammerAuthentication
.EXAMPLE
  Set-YammerAuthentication -ConsumerKey "cdQKyZcxNn6QnkkRsvYmKA" -ConsumerSecret "StLx7ktVrTq7u1z1zqntGyNKzPmoCKNNKZaASMmguCYg"
.PARAMETER ConsumerKey
  A value used by the Consumer to identify itself to the Service Provider Yammer. 
.PARAMETER ConsumerSecret
  A secret used by the Consumer to establish ownership of the Consumer Key.
.Link
  https://jammer.codeplex.com/
  http://railstips.org/blog/archives/2009/03/29/oauth-explained-and-what-it-is-good-for/
  #>
  
    [CmdletBinding(SupportsShouldProcess=$true)]
      param
      (
        [Parameter(
          HelpMessage='What is the Yammer Client Application Consumerkey?')]
        [string]$ConsumerKey,
        [Parameter(
          HelpMessage='What is the Yammer Client Application ConsumerSecret?')]
        [string]$ConsumerSecret
      )

    Write-Verbose "Function Set-YammerAuthentication started"

    Write-Verbose "Loading OAuth .Net Library"
    Add-Type -Path $JammerPath\DevDefined.OAuth.dll #change path to the location where you have downloaded the oAuth dll.

    #Check if you already have a session open.
    if($session)
    {
       $SessionResult = YammerMenu -title "You already have a Yammer session open" -message "Do you want to use you current Yammer session?" -yesoption "Uses current opened session" `
                  -noption "Create a new Session"
    

        if($SessionResult -eq 0)
        {
            "You selected Yes. Using current Yammer Session"; return
        
        }
        else
        {
            "You selected No. Creating new Yammer Session"

        }
    } #End if
    

    #Consumer token and secret are provided for you by the OAuth Yammer provider
    #Check registry for Consumer and Consumer Secret keys
    Write-Verbose "Check Registry if the Consumer and Consumer Secret keys are already stored"
    if(!(Test-Path -Path HKCU:\Software\Jammer))
    {
        Write-Output "You first need to register Yammer Application and store the Consumer and Consumer Secret keys on your machine `n `nGo to https://www.yammer.com/client_applications/new."
        start "https://www.yammer.com/client_applications/new"
        $ConsumerKey = Read-Host "Enter Yammer Application Consumer Key"
        $ConsumerSecret = Read-Host "Enter Yammer Application Consumer Secret"
        Write-Verbose "Storing Consumer and Consumer Secret keys in Registry HKCU:\Software\Jammer"
        #Store Consumer and Secret Key in Registry
        #Check if ConsumerKey and ConsumerSecret are not empty.
        if($ConsumerKey -and $ConsumerSecret)
        {
            New-Item -Path hkcu:\software -Name Jammer | out-null
            New-ItemProperty HKCU:\Software\Jammer -name "ConsumerKey" -value "$ConsumerKey" | out-null
            New-ItemProperty HKCU:\Software\Jammer -name "ConsumerSecret" -value "$ConsumerSecret" | out-null
        }
        else {write-error "Please retart Set-YammerAuthentication Function. One of the requested properties is empty"}
    }
    else
    {
        Write-Verbose "Retrieving Consumer Key and Consumer Secret from registry HKCU:\Software\Jammer"
        $ConsumerKey = (Get-Item HKCU:\Software\Jammer).getvalue("ConsumerKey")
        $ConsumerSecret = (Get-Item HKCU:\Software\Jammer).getvalue("ConsumerSecret")
        $Pin = (Get-Item HKCU:\Software\Jammer).getvalue("Pin")
    }

    #Request Token Part
    #In order to get the access token, you have to create a request token, keep track of it, and then redirect the user to the provider to authorize your application

    $cons = New-Object devdefined.oauth.consumer.oauthconsumercontext

    $cons.ConsumerKey = $ConsumerKey
    $cons.ConsumerSecret = $ConsumerSecret
    $cons.SignatureMethod = [devdefined.oauth.framework.signaturemethod]::HmacSha1


    $Global:session = new-object DevDefined.OAuth.Consumer.OAuthSession `
      $cons,
      "https://www.yammer.com/oauth/request_token",
      "https://www.yammer.com/oauth/authorize",
      "https://www.yammer.com/oauth/access_token"

    #Create Request Token.
    $requestToken = $session.GetRequestToken()

    #Authorization URL. The authorization URL is where your application redirects to, to allow the user to grant or deny you access to the their data.
    $userAuthorizationURLForToken = $session.GetUserAuthorizationUrlForToken($requestToken)

    #Open Browser for PIN
    Start-Process $userAuthorizationURLForToken

    $pin = read-host -prompt 'Enter PIN that you have seen at Yammer page'

    #Once the user is back at your app, you use the request token and pin to generate the access token
    $Global:accessToken = $session.ExchangeRequestTokenForAccessToken($requestToken, $pin)

    Write-Output "Creating Registry keys for storing the AccessToken info"
    New-Item -Path HKCU:\software\Jammer -Name AccessToken -Force | out-null
    New-ItemProperty HKCU:\Software\Jammer\AccessToken -name "TokenSecret" -value "$($AccessToken.TokenSecret)" -Force | out-null
    New-ItemProperty HKCU:\Software\Jammer\AccessToken -name "Token" -value "$($AccessToken.Token)" -Force | out-null
    New-ItemProperty HKCU:\Software\Jammer\AccessToken -name "ConsumerKey" -value "$($AccessToken.ConsumerKey)" -Force | out-null
    New-ItemProperty HKCU:\Software\Jammer\AccessToken -name "Realm"  | out-null
    New-ItemProperty HKCU:\Software\Jammer\AccessToken -name "Host InstanceId" -value "$($host.InstanceId)" -Force  | out-null

    Write-Output "Finished Yammer Authentication"
    Write-Verbose "Function Set-YammerAuthentication finished"


}



########################################################################################################################
# Get-YammerMessage
# 
#########################################################################################################################
Function Get-YammerMessage
{
<#
.SYNOPSIS
   Retrieve Yammer Messages
.DESCRIPTION
   Retrieves all messages in this network. Corresponds to the "Company Feed" tab on the website.
.EXAMPLE
  Get-YammerMessage | format-table @{L="Body";E={($_.Body).parsed}}, created_at -Wrap
.EXAMPLE
  Get-YammerMessage | Select-Object @{L="Body";E={($_.Body).parsed}}, created_at | Out-GridView
.EXAMPLE
  Get-YammerMessage -GroupName "PowerShell" | Select-Object @{L="Body";E={($_.Body).parsed}}, created_at | Out-GridView
.EXAMPLE
  Get-YammerGroup -Mine | Get-YammerMessage
  Retrieves all messages from all Yammer Groups you are a member of.
.PARAMETER GroupName
  The Get-YammerGroup function with the Group Parameter is being used to retrieve Group specific messages
.Link
  https://jammer.codeplex.com
  https://developer.yammer.com/restapi/#rest-messages
#>

    [CmdletBinding(SupportsShouldProcess=$true)]
      param(
		[Parameter(Mandatory=$False,
		ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True)]
		[string[]]$GroupName
	)

    Begin
    {
        Write-Verbose "Function Get-YammerMessage started"

        #Check if an AccessToken has been requested in this host session.

        if (($host.InstanceId).guid -ne (Get-Item HKCU:\Software\Jammer\AccessToken).getvalue("Host InstanceID"))
        {
            Write-Error "Use Set-YammerAuthentication first before requesting Yammer Messages"
        }
        else
        {
            $at = (Get-ItemProperty HKCU:\Software\Jammer\AccessToken)
            $accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
            $at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret

            $MyYammerGroups =Get-YammerGroup -Mine
        }

        


    }#End Begin

    Process
    {
        #Check if $GroupName is being used. If GroupName is being used retrieve Group Id from Get-YammerGroup Function.
        Write-Verbose "Checking if GroupName parameter is being used"
        If($GroupName)
        {
            Write-Verbose "Retrieving Group Id using Get-YammerGroup Function"
            #$MyYammerGroups =Get-YammerGroup -Mine
            if(!($MyYammerGroups.Groupname -contains $GroupName)){write-error "GroupName not found in your YammerGroups"}
            else
            {
                $GroupNameInfo = ($MyYammerGroups | Where-Object {$_.Groupname -like $GroupName}) | select Groupname, Id
                Write-Verbose "GroupName info is: $($GroupNameInfo)"
                $YammerParameter = "messages/in_group/$($GroupNameInfo.Id).json"

                Foreach ($group in $GroupName)
                {
                    Write-Debug "Yammer API call: https://www.yammer.com/api/v1/$YammerParameter"

                    $req = $session.Request($accessToken)
                    $req.Context.RequestMethod = 'GET'
                    $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/$YammerParameter"

                    $messages = $req | convertfrom-json -ErrorAction SilentlyContinue

                    ($messages | select Messages).messages

                } #End Foreach
            } # End Else

        }
        else
        {
            Write-Verbose "No GroupName parameter value found"
            $YammerParameter = "messages.json"
            Write-Debug "Yammer API call: https://www.yammer.com/api/v1/$YammerParameter"

            $req = $session.Request($accessToken)
            $req.Context.RequestMethod = 'GET'
            $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/$YammerParameter"

            $messages = $req | convertfrom-json -ErrorAction SilentlyContinue

            ($messages | select Messages).messages
        }
        
        
        


    } #End Process

    End
    {
        Write-Verbose "Function Get-YammerMessage finished"
    } #End End
   

}


########################################################################################################################
# Get-YammerGroup
# 
#########################################################################################################################
Function Get-YammerGroup
{
<#
.SYNOPSIS
  Retrieve Yammer Groups.
.DESCRIPTION
  Retrieve Yammer Groups. Maximum 50 Groups are shown at a time.
.EXAMPLE
  Get-YammerGroup -Mine
  Retrieves all the Yammer Groups you are a member of.
.EXAMPLE
  Get-YammerGroup -Page 1 -Letter "A"
  Retrieve the first page with 50 groups starting with the name "A"
.EXAMPLE
  Get-YammerGroup -Page 2 -Letter "A"
  Retrieve the second page with 50 groups starting with the name "A"
.EXAMPLE
  1..10 | Get-YammerGroup -Letter "A"
  Retrieve 10 pages with Yammer Groups starting with the name "A"
.Link
  https://jammer.codeplex.com
  https://developer.yammer.com/api/#groups
.NOTES
  History:
	v 0.1 - Changed default Name property to GroupName. This will help in the pipeline.
    v 0.2 - Created Parameter Sets 
#>

    [CmdletBinding(SupportsShouldProcess=$true)]
      param
      (
        [Parameter(ParameterSetName="Default",Position=0,
        Mandatory=$False,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='Number of groups which will be shown per page. Default 50 groups.')]
        [int[]]$Page,
        [Parameter(ParameterSetName="Default",Mandatory=$false,
          HelpMessage='Return groups beginning with the given letter.')]
        [string]$Letter,
        [Parameter(ParameterSetName="Mine",Mandatory=$false,
          HelpMessage='With the Mine Parameter only your Yammer Groups are shown.')]
        [switch]$Mine
      )

    Begin
    {

        Write-Verbose "Function Get-YammerGroup started"

        #Check if an AccessToken has been requested in this host session.

        if (($host.InstanceId).guid -ne (Get-Item HKCU:\Software\Jammer\AccessToken).getvalue("Host InstanceID"))
        {
            Write-Error "Use Set-YammerAuthentication first before requesting Yammer Messages"
        }
        else
        {
            $at = (Get-ItemProperty HKCU:\Software\Jammer\AccessToken)
            $accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
            $at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret
        }
    } #End Begin

    Process
    {
        Write-Verbose "Check if Page parameter is being used"
        if ($Page)
        {
            Write-Verbose "Page parameter is being used"
            Foreach ($Pagenumber in $Page)
            {
                 #Create API parameters
                Write-Verbose "Create API Parameters"
                if ($Mine)
                {
                    [int]$MineSwitch=1;$YammerParameter = "page=$Page&letter=$Letter&mine=$MineSwitch"
                }
                else
                {
                    $YammerParameter = "page=$PageNumber&letter=$Letter"
                }

                Write-Debug "Yammer API call: https://www.yammer.com/api/v1/groups.json?$YammerParameter"

                $req = $session.Request($accessToken)
                $req.Context.RequestMethod = 'GET'
                $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/groups.json?$YammerParameter"
                $groups = $req | convertfrom-json -ErrorAction SilentlyContinue

                $groups | select @{L="Groupname";E={$_.Name}}, Id, Description, Privacy, @{L="Members"; E={($_ | select -ExpandProperty Stats).Members}}

           } #End Foreach
        } #End if
        else
        {
            Write-Verbose "Page parameter is not being used"
            #Create API parameters
            Write-Verbose "Create API Parameters"
            if ($Mine){[int]$MineSwitch=1;$YammerParameter = "letter=$Letter&mine=$MineSwitch"}
            else
            {
                $YammerParameter = "letter=$Letter"
            }

                Write-Debug "Yammer API call: https://www.yammer.com/api/v1/groups.json?$YammerParameter"

                $req = $session.Request($accessToken)
                $req.Context.RequestMethod = 'GET'
                $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/groups.json?$YammerParameter"
                $groups = $req | convertfrom-json -ErrorAction SilentlyContinue

                #$groups | select full_name, description, id
                $groups | select @{L="Groupname";E={$_.Name}}, Id, Description, Privacy, @{L="Members"; E={($_ | select -ExpandProperty Stats).Members}}
         } #End else                                           


    } #End Process
    
    End
    {
        Write-Verbose "Function Get-YammerGroup Finished"
    }
       

}


########################################################################################################################
# Send-YammerMessage
# 
#########################################################################################################################
Function Send-YammerMessage
{
<#
.SYNOPSIS
   Send Yammer Messages
.DESCRIPTION
   Send Yammer Message to Network or to specified Yammer Group
.EXAMPLE
  Send-YammerMessage -Message "How cool is this? Publishing messages on Yammer using PowerShell!" -GroupName "PowerShell"
.EXAMPLE
  Get-YammerGroup -Mine | Send-YammerMessage -Message "How cool is this? Publishing messages on Yammer using PowerShell!"
  Sending the same message to all your Yammer Groups at once.
  Be careful using this. You could be called a spammer ;-)
.PARAMETER Groupname
  Yammer GroupName from your Yammer Groups.
  The Yammer Groupname where you are a member of.
.Link
  https://jammer.codeplex.com
  https://developer.yammer.com/api/#messages-manipulating
  #>


  [CmdletBinding(SupportsShouldProcess=$true)]
      param
      (
        [Parameter(Mandatory=$True,
        ValueFromPipeline=$False,
        ValueFromPipelineByPropertyName=$False,
          HelpMessage='What is the message you want to publish on Yammer?')]
        [string[]]$Message,
        [Parameter(Mandatory=$false,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='What is the Yammer Group you want to publish on Yammer? If you don not a enter a group the Network root group is used.')]
        [string[]]$GroupName
      )

      Begin
      {
            Write-Verbose "Function Send-YammerMessage started"

            #Check if an AccessToken has been requested in this host session.

            if (($host.InstanceId).guid -ne (Get-Item HKCU:\Software\Jammer\AccessToken).getvalue("Host InstanceID"))
            {
                Write-Error "Use Set-YammerAuthentication first before requesting Yammer Messages"
            }
            else
            {
                $at = (Get-ItemProperty HKCU:\Software\Jammer\AccessToken)
                $accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
                $at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret

                #Retrieve Yammer Groups for user.
                $youryammergroups =Get-YammerGroup -Mine
            }
      } # End Begin

      Process
      {
            #Check Yammer Group
			if ($GroupName) #if no group parameter is used the message is posted to the root group of the network
			{
				#$youryammergroups = Get-YammerGroup -Mine
				if (!($youryammergroups | where {$_.Groupname -like $GroupName}))
				{
					write-error "You are not a member of such a group"
				}
				else
				{
					$GroupName = ($youryammergroups | where {$_.Groupname -like $GroupName}).id
					
					Foreach ($group in $GroupName)
                    {
                        Write-Debug "Yammer API call: https://www.yammer.com/api/v1/messages.json?body=$Message&group_id=$GroupName"

                        #Post a message
                        $post = $session.Request($accessToken)
                        $post.Context.RequestMethod = 'POST'
                        $post.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/messages.json?body=$Message&group_id=$GroupName"
                        $post | ConvertFrom-Json | select -ExpandProperty Messages
                        #"Yammer API call: https://www.yammer.com/api/v1/messages.json?body=$Message&group_id=$GroupName"

                    } #End Foreach
					
				} # End Else
			} # End If

            else
            {
                Write-Verbose "No GroupName parameter value found. Sending message to default network"
                Write-Debug "Yammer API call: https://www.yammer.com/api/v1/messages.json?body=$Message"

                #Post a message
                $post = $session.Request($accessToken)
                $post.Context.RequestMethod = 'POST'
                $post.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/messages.json?body=$Message"
                $post | ConvertFrom-Json | select -ExpandProperty Messages
                #"Yammer API call: https://www.yammer.com/api/v1/messages.json?body=$Message"
            } #End Else
        } #End Process
        
        End
        {
            Write-Verbose "Function Send-YammerMessage Ended"
        } #End End

    
}




########################################################################################################################
# Get-YammerUser
# 
#########################################################################################################################
Function Get-YammerUser
{
<#
.SYNOPSIS
   Get Yammer User Information
.DESCRIPTION
   Get Yammer User Information using an email address as parameter
.EXAMPLE
  Get-YammerUser -Email "john.doe@contoso.com"
  Retrieve the Yammer User Information for user with email address "john.doe@contoso.com"
.EXAMPLE
  "john.doe@contoso.com", "richard.niks@contoso.com" | Get-YammerUser
  Retrieve the Yammer User Information for user with email address "john.doe@contoso.com" and "richard.niks@contoso.com"
  in a pipeline.
.EXAMPLE
  Get-YammerUser -InGroup 856015
  Retrieve the Users for Group ID 856015.
.EXAMPLE
  1..10 | Get-YammerUser -InGroup 856015
  Retrieve the first 10 pages with Users for Group Id 856015
.EXAMPLE
  Get-YammerUser -InGroup 2044380 | %{Get-YammerUser -id $_.id}
  Get Yammer user information (like email addresses) for all members of a Yammer Group
.PARAMETER Email
  The email address of the user on Yammer for which you want to retrieve the User Information
.PARAMETER Id
  The Yammer User Id.
.PARAMETER InGroup
  The Group Id for which you want to retrieve the member users.
.PARAMETER Page
  The Page number for which you to retrieve the Group Member Users for.
.Link
  https://jammer.codeplex.com
  https://developer.yammer.com/restapi/#rest-users
  #>

  [CmdletBinding(SupportsShouldProcess=$true)]
      param
      (
        [Parameter(Mandatory=$False,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='What is the email address of the Yammer User?')]
        [string]$Email,
        [Parameter(Mandatory=$False,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='What is the Id of the Yammer User?')]
        [string]$Id,
        [Parameter(Mandatory=$False,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='What is the Yammer Group ID for which you want to retrieve the users?')]
        [int[]]$InGroup,
        [Parameter(Mandatory=$False,
        ValueFromPipeline=$True,
        ValueFromPipelineByPropertyName=$True,
          HelpMessage='Number of Users per Group which will be shown per page. Default 50 groups.')]
        [int[]]$Page=1
      )

    Begin
    {

        Write-Verbose "Function Get-YammerUser started"

        #Check if an AccessToken has been requested in this host session.

        if (($host.InstanceId).guid -ne (Get-Item HKCU:\Software\Jammer\AccessToken).getvalue("Host InstanceID"))
        {
            Write-Error "Use Set-YammerAuthentication first before requesting Yammer Messages"
        }
        else
        {
            $at = (Get-ItemProperty HKCU:\Software\Jammer\AccessToken)
            $accessToken.ConsumerKey, $accessToken.Realm, $accessToken.Token, $accessToken.TokenSecret = `
            $at.ConsumerKey, $at.Realm, $at.Token, $at.TokenSecret
        }
    }

    Process
    {
       #Check if single user info is requested or Group Membership
       if ($email -and (!$InGroup)){
           Foreach ($user in $Email)
           {
                Write-Verbose "Checking Yammer User info for user: $($user)"
                Write-Verbose "Yammer API call: https://www.yammer.com/api/v1/by_email.json?email=$Email"

                #Post a message
                $req = $session.Request($accessToken)
                $req.Context.RequestMethod = 'GET'
                $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/users/by_email.json?email=$Email"
                #$user = $req | convertfrom-json -ErrorAction SilentlyContinue
                #$($req.ToWebResponse().StatusCode)
                $user = $req | convertfrom-json
                $user | select full_name, name, id, network_name, job_title, state, activated_at, timezone,
                        @{L="Updates"; E={($_ | select -ExpandProperty Stats).Updates}}, 
                        @{L="Following"; E={($_ | select -ExpandProperty Stats).Following}},
                        @{L="Followers"; E={($_ | select -ExpandProperty Stats).Followers}},
                        @{L="EmailAddress"; E={($_ | select -ExpandProperty contact | 
                                select email_addresses | select -ExpandProperty email_addresses).address}}

            
                Sleep 1 #Needed to build in a short delay because the api could not keep up with some of the requests
            }#End foreach'
        } #End if
        if($Id)
        {
           Foreach ($user in $id)
           {
                Write-Verbose "Checking Yammer User info for Id: $($user)"
                Write-Verbose "Yammer API call: https://www.yammer.com/api/v1/users/$user.json"

                #Post a message
                $req = $session.Request($accessToken)
                $req.Context.RequestMethod = 'GET'
                $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/users/$user.json"
                #$user = $req | convertfrom-json -ErrorAction SilentlyContinue
                #$($req.ToWebResponse().StatusCode)
                $user = $req | convertfrom-json
                $user | select full_name, name, id, network_name, job_title, state, activated_at, timezone,
                        @{L="Updates"; E={($_ | select -ExpandProperty Stats).Updates}}, 
                        @{L="Following"; E={($_ | select -ExpandProperty Stats).Following}},
                        @{L="Followers"; E={($_ | select -ExpandProperty Stats).Followers}},
                        @{L="EmailAddress"; E={($_ | select -ExpandProperty contact | 
                                select email_addresses | select -ExpandProperty email_addresses).address}}

            
                Sleep 1 #Needed to build in a short delay because the api could not keep up with some of the requests
            }#End foreach'

        }
        else
        {
            Foreach ($GroupId in $InGroup)
           {
                Write-Verbose "Checking Yammer User MemberShip for GroupID: $($GroupId)"
                Write-Verbose "Yammer API call: https://www.yammer.com/api/v1/users/in_group/$GroupId.json?page=$Page"

                #Request API call
                $req = $session.Request($accessToken)
                $req.Context.RequestMethod = 'GET'
                $req.Context.RawUri = [Uri]"https://www.yammer.com/api/v1/users/in_group/$GroupId.json?page=$Page"
                $req | convertfrom-json | select -ExpandProperty users | select Name, full_name,id,state
           
                Sleep 1 #Needed to build in a short delay because the api could not keep up with some of the requests
            }#End foreach'
            

        }#End Else

    } #End Process

    End
    {

        Write-Verbose "Function Get-YammerUser Ended"
    }


}


########################################################################################################################
# YammerMenu
# A Simple Menu to be used within the Yammer Functions.
#########################################################################################################################
Function YammerMenu
{

    param([string]$title,[string]$message,[string]$yesoption,[string]$noption)
    #$title = "Delete Files"
    #$message = "Do you want to delete the remaining files in the folder?"

    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
    $yesoption

    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    $noption

    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

    $host.ui.PromptForChoice($title, $message, $options, 0)  

}

#Main
$Global:JammerPath = Split-Path -parent $MyInvocation.MyCommand.Definition